<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 信誉付
 */
class XinyufuController extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));

        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $isMobile = isMobile();

        $return = $this->orderadd( $parameter );

        $data = array();
        $data['V'] = 'V4.0';
        $data['UserNo'] = $this->config['mch_id'];
        $data['ordNo'] = $return['orderid'];
        $data['ordTime'] = date("YmdHis",time());
        $data['amount'] = intval($return['amount'] * 100);
        $data['pid'] = 'apzf';
        $data['notifyUrl'] = $return['notifyurl'];
        $data['frontUrl'] = $return['callbackurl'];
        $data['remark'] = '18123663214';
        $data['ip'] = getIP();


        $str = "";
        foreach($data as $k=>$v){
            $str .= $v."|";
        }
        $str .= $this->config['signkey'];
        $data['sign'] = strtoupper(md5($str));

        $res = curl($this->config['gateway'], httpstr($data));

        if(!$res){
            $this->showmessage('未获取到返回数据!',['code'=>C("THIRDCODES.".$this->class)]);
        }
        $res = json_decode($res, true);

        //echo '<pre/>'; print_r($res); exit;

        $code = $res['Payurl'];
        if(!$code){
            if($res['resMsg']){
                $this->showmessage($res['resMsg'],['code'=>C("THIRDCODES.".$this->class)]);
            }
            $this->showmessage('获取支付链接失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }


        if($isMobile){
            header("Location: {$code}"); exit;
        }

        $paytype = transArr( C("PAYTYPES"), "id");

        //$this->assign("code_url", $code);
        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
        $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?type=1&data=" . $code);

        switch($this->config['paytype']){
            //微信
            case 1:
                $this->display("WeiXin/weixin");
                break;
            //支付宝扫码
            case 3:
                $this->display("WeiXin/alipay");
                break;
            //支付宝H5
            case 4:
                $this->display("WeiXin/alipay");
                break;
            //支付宝
            case 17:
                $this->display("WeiXin/alipay");
                break;
            //支付宝H5
            case 18:
                $this->display("WeiXin/alipay");
                break;
            default:
                $this->display("WeiXin/Pay");
        }
    }

    //通知
    public function notifyurl(){
        //file_put_contents("a.txt","post: ".var_export($_POST,true)."\r\n\r\n");
        //file_put_contents("a.txt","post_i: ".var_export(I("post."),true)."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt","get: ".var_export($_GET,true)."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", "input: ".file_get_contents('php://input')."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", "time: ".date("Y-m-d H:i:s",time())."\r\n\r\n", FILE_APPEND);

        $p = $origin = $_POST;

        /*$p = $origin =array (
            'msg' => '000|{"createTime":"20181030203359","errorMsg":"","extend":"remark=18123663214","orderFinishTime":"20181030203410","orderId":530606,"orderStatus":1,"orderSuccAmount":11.00,"payments":[{"itemNum":1,"itemResponseMsg":{"barcodeInfo":"https://qr.alipay.com/bax01836cnjcybjwehtm403c","barcodeUrl":"http://119.28.38.124/fcrpc/barcode/zfb/639244.htm"},"itemStatus":1,"itemSuccAmount":11.00}],"traceNO":"201810302033552785239"}|e4dcd4da0eae0cfd4ed919b59398aaf6bb4af9124f30cc07427c2416234e3780',
        );*/

        if(!$p){
            exit("wrong");
        }

        $p = $p['msg'];
        $p = explode("|", $p);
        $status = $p[0];
        $json = $p[1];
        $sign = $p[2];
        $p = json_decode($p[1], true);

        /*
         * Array
(
    [createTime] => 20181030194555
    [errorMsg] =>
    [extend] => remark=18123663214
    [orderFinishTime] => 20181030194609
    [orderId] => 530339
    [orderStatus] => 1
    [orderSuccAmount] => 10
    [payments] => Array
        (
            [0] => Array
                (
                    [itemNum] => 1
                    [itemResponseMsg] => Array
                        (
                            [barcodeInfo] => https://qr.alipay.com/bax07406iejpptp5w1gy806f
                            [barcodeUrl] => http://119.28.38.124/fcrpc/barcode/zfb/638976.htm
                        )

                    [itemStatus] => 1
                    [itemSuccAmount] => 10
                )

        )

    [traceNO] => 201810301945491942896
)
         */

        if(!$p || empty($p)){
            exit("wrong");
        }

        //获取订单信息
        $orderid = $p['traceNO'];
        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(

            "pay_orderid_rd"=> htmlspecialchars($p['orderId'])
        ));

        //获取渠道信息
        $this->config = M("Channel")->where(array('code'=>'Xinyufu'))->find();

        $str = $json . $this->config['signkey'];

        if($status !== '000'){
            exit("pay_fail");
        }

        $sign2 = hash("sha256", $str);

        /*echo '<pre/>';
        print_r($p);
        echo "status: ". $status."<br/>";
        echo "str: " . $str ."<br/><br/>";
        echo "sign: " .$sign ."<br/>";
        echo "sign2:". $sign2 ."<br/>";
        */

        if($sign !== $sign2){
            exit("sign_wrong");
        }

        if($p['status'] != 0){
            exit("pay_fail");
        }

        //处理支付
        $this->EditMoney($find['pay_orderid'],"Xinyufu",0);

        //回调成功
        echo "OK"; exit;
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}